package com.ayou.healthmanagement.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import lombok.SneakyThrows;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class
ExcelUtil {
    static ArrayList<String> errorNames = new ArrayList<>();
    /**
     * 导出excel
     *
     * @param response
     * @return
     */
    @SneakyThrows
    public static<T> void download(HttpServletResponse response, List<T> list, Class<T> clazz) {
//        response.setContentType("application/vnd.ms-excel");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("角色信息", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), clazz)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())//自适应表格格式
                .sheet()
                .doWrite(list);
    }
}
